package com.tts.biz;

import org.hibernate.Transaction;

import com.tts.hbdao.UserDAO;
import com.tts.hbentity.User;

public class UserBiz {

	public User user;
	public UserDAO userDao;

	/**
	 * Initialize
	 */
	public void init() {
		user = new User();
		userDao = new UserDAO();
	}

	/**
	 * Register A New User
	 * 
	 * @param userName
	 * @param userEmail
	 * @param userPwd
	 * @param userAddress
	 * @param userSex
	 * @param userTel
	 * @param userCard
	 * @return true/false, means success/fail
	 */
	public boolean userReg(String userName, String userEmail, String userPwd,
			String userAddress, Byte userSex, Long userTel, Long userCard) {

		// 1. Create Instance
		user.setUserName(userName);
		user.setUserEmail(userEmail);
		user.setUserPwd(userPwd);
		user.setUserAddress(userAddress);
		user.setUserSex(userSex);
		user.setUserTel(userTel);
		user.setUserCard(userCard);

		// 2. Start the transaction
		Transaction tx = userDao.getSession().beginTransaction();

		// 3. Add Instance
		userDao.save(user);

		// 4. Commit the transaction (write to database)
		tx.commit();

		// 5. Close the session (cleanup connections)
		userDao.getSession().close();

		return true;
	}

	/**
	 * Whether A User is Existent or not
	 * 
	 * @param userEmail
	 * @param userPwd
	 * @return a user entity or null
	 */
	public User userIsExistent(String userEmail, String userPwd) {

		// 1. Create Instance
		user.setUserEmail(userEmail);
		user.setUserPwd(userPwd);

		// 2. Start the transaction
		Transaction tx = userDao.getSession().beginTransaction();

		// 3. Search By This Instance, And Return A Instance List
		java.util.List<User> userList = userDao.findByExample(user);

		// 4. Commit the transaction (write to database)
		tx.commit();

		// 5. Close the session (cleanup connections)
		userDao.getSession().close();

		// 6. Estimate The Result
		if (userList.isEmpty()) {
			return null;
		} else {
			return userList.get(0);
		}
	}

	/**
	 * Delete A User
	 * 
	 * @param user
	 * @return true/false, means success/fail
	 */
	public boolean deleteUser(User user) {

		// 1. Start the transaction
		Transaction tx = userDao.getSession().beginTransaction();

		// 2. Delete Instance
		userDao.delete(user);

		// 3. Commit the transaction (write to database)
		tx.commit();

		// 4. Close the session (cleanup connections)
		userDao.getSession().close();

		return true;
	}

	/**
	 * Modify User's Information
	 * @param user
	 * @return
	 */
	public boolean userModify(User user) {
		
		// 1. Start the transaction
		Transaction tx = userDao.getSession().beginTransaction();

		// 2. Modify Instance
		userDao.attachDirty(user);

		// 3. Commit the transaction (write to database)
		tx.commit();

		// 4. Close the session (cleanup connections)
		userDao.getSession().close();

		return true;
	}
}
